<template>
  <div class="tabs-item">
    <div class="add-role">
      <el-button type="primary" @click="addRole" plain>新增角色</el-button>
    </div>
    <div class="page-list">
      <el-table height="100%" :data="tableData" stripe style="width: 100%">
        <el-table-column prop="" label="" width="30"> </el-table-column>
        <el-table-column prop="name" label="角色名称"> </el-table-column>
        <el-table-column prop="desc" label="角色描述"> </el-table-column>
        <el-table-column prop="update_at" label="最近更新时间">
        </el-table-column>
        <el-table-column prop="" label="操作" width="150">
          <template slot-scope="scope">
            <div class="btn-group">
              <div class="btn-item" @click="saveRole(scope.row)">编辑</div>
              <div class="btn-item" @click="delRole(scope.row)">删除</div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page">
      <el-pagination background layout="prev, pager, next" :page-size="num" :current-page.sync="page" :total="total"
        @current-change="pageChange">
      </el-pagination>
    </div>

    <!-- 角色编辑弹窗 -->
    <el-dialog :title="editRoleType == 'add' ? '添加角色' : '修改角色'" :visible.sync="editRoleVisible" width="1000px">
      <div class="role-main">
        <el-form :model="roleInfoform" ref="saveRole" :rules="roleInfoRules" :inline="true" class="role-info">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleInfoform.name" placeholder="请输入角色名称"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="desc">
            <el-input v-model="roleInfoform.desc" placeholder="请输入角色描述(非必填)"></el-input>
          </el-form-item>
        </el-form>
        <div class="perlabel">权限列表</div>
        <div v-if="!perList.length" style="margin-left: 10px">
          暂无权限，请前往 "<span class="jump" @click="jump">项目权限</span>"
          添加！
        </div>
        <div class="permission-list" v-else>
          <el-checkbox-group v-model="roleInfoform.checkedList">
            <div class="item-tr" v-for="(item, index) in perList" :key="index">
              <div class="item1-td">{{ item.name }}</div>
              <div class="item2-td">
                <div class="item2-tr" v-for="(item2, index2) in item.nodes" :key="index2">
                  <div class="item2-td-main">
                    <el-tooltip class="item" effect="dark" :content="item2.name" placement="right">
                      <div class="item2-td-name">
                        <el-checkbox :label="item2.id" @change="checkAll($event, index, index2)">{{ item2.name }}
                        </el-checkbox>
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="item3-td">
                    <div class="item-fun" v-for="(item3, indx3) in item2.operation" :key="indx3">
                      <el-checkbox :label="item3.id">{{
                        item3.name
                      }}</el-checkbox>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-checkbox-group>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sumbit" :loading="roleInfoform.submitBtn">提交</el-button>
        <el-button @click="editRoleVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import permissionApi from "@/api/permissionApi";

  export default {
    name: "",
    props: [],
    data() {
      return {
        loading: false,
        // 用户列表数据
        page: 1,
        num: 10,
        total: 0,
        tableData: [],

        // 权限列表数据
        perList: [],
        // 角色编辑弹窗
        editRoleVisible: false,
        editRoleType: "add",
        roleInfoform: {
          id: "",
          name: "",
          desc: "",
          checkedList: [],
          submitBtn: false,
        },
        roleInfoRules: {
          name: [{
            required: true,
            message: "请输入角色名称",
            trigger: "change"
          }, ],
        },
      };
    },
    watch: {},
    mounted() {
      this.getPermissionList();
      this.getRoleList();
    },
    methods: {
      // 获取权限列表
      getPermissionList() {
        permissionApi.getPermissionList().then((res) => {
          console.log(res, "getPermissionList");
          if (res.code == 200) {
            this.perList = res.data;
          }
        });
      },
      // 选择分页
      pageChange(page) {
        this.page = page;
        this.getRoleList();
      },
      // 添加角色
      addRole() {
        this.editRoleType = "add";
        this.editRoleVisible = true;
        this.roleInfoform.checkedList = [];
        this.$nextTick(() => {
          this.$refs.saveRole.resetFields();
        });
      },
      // 编辑角色
      saveRole(row) {
        this.editRoleType = "edit";
        permissionApi
          .getRoleInfo({
            id: row.id,
          })
          .then((res) => {
            console.log(res, "getRoleInfo");
            if (res.code == 200) {
              this.roleInfoform.id = row.id;
              this.roleInfoform.name = res.data.name;
              this.roleInfoform.desc = res.data.desc ? res.data.desc : "";
              this.roleInfoform.checkedList = res.data.checkedList;
              this.editRoleVisible = true;
            } else {
              this.$message.error(res.message);
            }
          });
      },

      checkAll(state, idx, idx2) {
        console.log(state, idx, idx2,"state, idx, idx2")
        let perList = this.perList;
        let operation = perList[idx].nodes[idx2].operation;
        if (state) {
          this.setChecked(operation);
        } else {
          this.setUnChecked(operation);
        }
      },
      // 设置全不选
      setUnChecked(data) {
        let checkedList = this.roleInfoform.checkedList;
        data.forEach((item) => {
          if (checkedList.includes(item.id)) {
            var index = checkedList.indexOf(item.id);
            checkedList.splice(index, 1);
          }
        });
      },
      // 设置全选
      setChecked(data) {
        let checkedList = this.roleInfoform.checkedList;
        data.forEach((item) => {
          if (!checkedList.includes(item.id)) {
            checkedList.push(item.id);
          }
        });
      },

      jump() {
        this.editRoleVisible = false;
        this.$emit("change", "second");
      },
      // 修改perList数组变成一维
      setArrayFormat() {
        let perList = this.perList;
        let arr = [];
        perList.forEach((item) => {
          item.nodes.forEach((item2) => {
            var obj = {};
            obj.id = item2.id;
            obj.pid = item2.parent_id;
            arr.push(obj);
            item2.operation.forEach((item3) => {
              var obj = {};
              obj.id = item3.id;
              obj.pid = item3.parent_id;
              arr.push(obj);
            });
          });
        });
        return arr;
      },
      // 获取角色列表
      getRoleList() {
        permissionApi
          .getRoleList({
            page: this.page,
            num: this.num,
          })
          .then((res) => {
            console.log(res, "getRoleList");
            this.loading = true;
            if (res.code == 200) {
              this.tableData = res.data.list;
              this.total = res.data.max;
            }
          })
          .catch((err) => {
            this.$message({
              message: err.message,
              type: "warning",
            });
          });
      },
      setRoleAdd(roleInfoform, checked_arr) {
        permissionApi
          .setRoleAdd({
            name: roleInfoform.name,
            desc: roleInfoform.desc,
            checked_arr: JSON.stringify(checked_arr),
          })
          .then((res) => {
            console.log(res, "setRoleAdd");
            if (res.code == 200) {
              this.$message({
                message: "添加成功",
                type: "success",
              });
              this.editRoleVisible = false;
              this.getRoleList();
            } else {
              this.$message.error(res.message);
            }
            this.roleInfoform.submitBtn = false;
          });
      },
      setRoleSave(roleInfoform, checked_arr) {
        permissionApi
          .setRoleSave({
            id: roleInfoform.id,
            name: roleInfoform.name,
            desc: roleInfoform.desc,
            checked_arr: JSON.stringify(checked_arr),
          })
          .then((res) => {
            console.log(res, "setRoleAdd");
            if (res.code == 200) {
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.editRoleVisible = false;
              this.getRoleList();
            } else {
              this.$message.error(res.message);
            }
            this.roleInfoform.submitBtn = false;
          });
      },
      sumbit() {
        this.$refs.saveRole.validate((valid) => {
          if (valid) {
            let roleInfoform = this.roleInfoform;
            // 选中的处理格式
            let checkedList = roleInfoform.checkedList;
            if (checkedList.length < 1) {
              this.$message({
                message: "请选择至少一个权限",
                type: "warning",
              });
              return;
            }
            this.roleInfoform.submitBtn = true;
            let perList = this.setArrayFormat();
            let checked_arr = [];

            perList.forEach((item) => {
              if (checkedList.includes(item.id)) {
                checked_arr.push(item);
              }
            });
            if (this.editRoleType == "add") {
              this.setRoleAdd(roleInfoform, checked_arr);
            } else {
              this.setRoleSave(roleInfoform, checked_arr);
            }
          } else {
            return false;
          }
        });
      },
      delRole(row) {
        this.$confirm('是否删除 "' + row.name + '" 角色?', "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            permissionApi
              .setRoleDel({
                id: row.id,
              })
              .then((res) => {
                console.log(res, "setRoleDel");
                if (res.code == 200) {
                  this.$message({
                    type: "success",
                    message: "删除成功!",
                  });
                  this.getRoleList();
                } else {
                  this.$message.error(res.message);
                }
              });
          })
          .catch(() => {});
      },
    },
  };

</script>

<style lang="scss" src="./index.scss" scoped></style>
